import { defineStore } from 'pinia'
import { ref } from 'vue'

interface CartItem {
  id?: number
  name: string
  price: number
  image: string
  quantity: number
  spiceLevels?: string[]
  selected?: boolean
}

export const useCartStore = defineStore('cart', () => {
  const items = ref<CartItem[]>([])
  const totalItems = ref(0)
  const totalPrice = ref(0)

  function addItem(item: Omit<CartItem, 'quantity'> & { spiceLevels?: string[] }) {
    const existingItem = items.value.find(i => 
      i.id === item.id && 
      JSON.stringify(i.spiceLevels?.sort()) === JSON.stringify(item.spiceLevels?.sort())
    )
    
    if (existingItem) {
      existingItem.quantity += 1
    } else {
      items.value.push({ ...item, quantity: 1 })
    }
    
    updateTotals()
  }

  function removeItem(id: number) {
    items.value = items.value.filter(item => item.id !== id)
    updateTotals()
  }

  function updateQuantity(id: number, quantity: number) {
    const item = items.value.find(item => item.id === id)
    if (item) {
      item.quantity = quantity
      updateTotals()
    }
  }

  function clearCart() {
    items.value = []
    updateTotals()
  }

  function updateTotals() {
    totalItems.value = items.value.reduce((sum, item) => sum + item.quantity, 0)
    totalPrice.value = items.value.reduce((sum, item) => sum + (item.price * item.quantity), 0)
  }

  return {
    items,
    totalItems,
    totalPrice,
    addItem,
    removeItem,
    updateQuantity,
    clearCart
  }
})
